package javanio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * Created by IntelliJ IDEA.
 * User: liuliwei
 * Date: 2017-09-21
 * Time: 上午10:10
 * Description: ${description}
 */
public class ChannelAccept {

    public static final String GREETING = "Hello I must be going";

    public static void main(String[] args) throws IOException, InterruptedException {
        int port =1234 ;
        if (args.length>0) {
            port = Integer.parseInt(args[0]);
        }

        ByteBuffer buffer =ByteBuffer.wrap(GREETING.getBytes());
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        serverSocketChannel.configureBlocking(false);
        while (true) {
            System.out.println("Waiting for connections");
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel == null) {
                Thread.sleep(1000);
            } else {
                System.out.println("Incoming connection from :" + socketChannel.socket().getRemoteSocketAddress());
                buffer.rewind();
                socketChannel.write(buffer);
                socketChannel.close();
            }
        }
    }
}
